package com.sjsu.aws.rendavu;

import java.util.Map;

import com.sjsu.aws.simplocks.NodeId;

/**
 * 
 * @author Shweta Dattatreya
 * 
 */

public class Worker extends Thread {
	private String id;
	public String name;
	private AWSClient client;
	private Watcher watcher;
	private boolean exit;

	private class WatcherImpl implements Watcher {
		public void updated() {
			System.out
					.println("Worker getting updated with Master's Address & Port number");
			System.out.println("Address updated. Reading new values");
			getAddrInfo();
		}

		public void deleted() {
			exit = true;
		}
	}

	/**
	 * 
	 * @param node
	 * @throws Exception
	 */
	public Worker(String node) throws Exception {
		id = node;
		watcher = new WatcherImpl();
		client = AWSClient.getInstance();
		name = NodeId.getId();
		synchronized (client) {
			client.addWatcher(watcher);
		}
		getAddrInfo();
	}

	void getAddrInfo() {
		synchronized (client) {
			try {
				Map<String, String> item = client.queryItem(id);
				String addr = item.get("ADDRESS");
				String port = item.get("PORT");
				System.out
						.println("Master Address: " + addr + " Port: " + port);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void run() {
		try {
			while (!exit) {
				Thread.sleep(10 * 1000);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Worker Exiting");
	}

}
